/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-12-27
 * Time: 20:33
 */
/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution5 {
    public ListNode reverseKGroup(ListNode head, int k) {
        // 第一步计算需要逆序多少组
        int n = 0;
        ListNode cur = head;
        while(cur != null){
            n++;
            cur = cur.next;
        }
        n = n/k;//逆序组数
        ListNode tmp = head;
        ListNode ret = new ListNode(0);
        ListNode prev = ret;
        while(n != 0){
            ListNode move = tmp;
            while(k != 0){
                //执行k次头插法
                ListNode next = tmp.next;
                tmp.next = prev.next;
                prev.next = tmp;
                tmp = next;
                k--;
            }
            prev = move;
            n--;
        }
        prev.next = tmp;
        return ret.next;

    }
}
public class Test5 {
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        Solution5 solution5 = new Solution5();
        solution5.reverseKGroup(node1,2);


    }
}
